// pages/life/life.js
const app = getApp()
import Notify from '@vant/weapp/notify/notify';
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		dynamics: [],
		mine: [],
		userInfo: {},
		//分页查询变量初始值
		offset: 0,
		score: Date.parse(new Date()),
		index: 0,
		modalName:'',
    temp:'',
    loadModal:true
	},

	onLoad() {
		// if (this.data.index == 0) {
		// 	this.setData({
		// 		dynamics: [],
		// 		offset: 0,
		// 		score: Date.parse(new Date()),
		// 	}) //更新上一个页面列表数据为空
		// 	this.getAllDynamicsByOffsetAndScore()
		// } else {
		// 	this.setData({
		// 		mine: [],
		// 		offset: 0,
		// 		score: Date.parse(new Date()),
		// 	})
		// 	this.getMyDynamicsByOffsetAndScore()
		// }
	},
	onShow() {
		console.log('onshow执行了')
		this.getTabBar().init();
		//初始化，获取全部动态的第一页
		if (this.data.index == 0) {
			this.setData({
				dynamics: [],
				offset: 0,
				score: Date.parse(new Date()),
			}) //更新上一个页面列表数据为空
			this.getAllDynamicsByOffsetAndScore()
		} else {
			this.setData({
				mine: [],
				offset: 0,
				score: Date.parse(new Date()),
			})
			this.getMyDynamicsByOffsetAndScore()
		}
		this.setData({
			userInfo: wx.getStorageSync('user')
		})
		var info = this.data.userInfo
		if (info == null || info == '') {
			console.log('未登录')
			//调用接口获取用户基本信息，并保存在storage中去
			app.request({
				url: app.globalData.apiUrl + "/user/get",
				method: 'GET',
			}).then(res => {
				if (res.statusCode == 200) {
					wx.setStorageSync('user', res.data.data)
					this.setData({
						userInfo: wx.getStorageSync('user')
					})
				} else {
					Notify('服务错误，稍后重试');
				}
			})
		}
	},
	//下滑获取动态，注意判断当前页面,决定调用哪个方法
	onReachBottom: function () {
		if (this.data.score == null || '' || undefined) {
			console.log('没有过呢更多啦')
		} else {
			if (this.data.index == 0) {
				this.getAllDynamicsByOffsetAndScore()
			} else {
				this.getMyDynamicsByOffsetAndScore()
			}
		}
	},
	//根据时间获取所有动态
	getAllDynamicsByOffsetAndScore() {
		if (this.data.offset == null || '') {
      console.log('没有过呢更多啦')
      this.setData({
        loadModal:false
      })
		} else {
			app.request({
				url: app.globalData.apiUrl + '/dynamic/all/' + this.data.offset + '/' + this.data.score,
				method: 'GET',
			}).then(res => {
				if (res.statusCode == 200) {
					this.setData({
						dynamics: res.data.data.list == null ? this.data.dynamics : this.data.dynamics.concat(res.data.data.list),
						offset: res.data.data.offset,
            score: res.data.data.minTime,
            loadModal:false
					})
				} else {
          this.setData({
            loadModal:false
          })
					Notify('服务错误，稍后重试');
				}
			})
		}
	},
	//根据时间获取所有动态
	getMyDynamicsByOffsetAndScore() {
		if (this.data.offset == null || '') {
      console.log('没有过呢更多啦')
      this.setData({
        loadModal:false
      })
		} else {
			app.request({
				url: app.globalData.apiUrl + '/dynamic/' + this.data.userInfo.id + '/' + this.data.offset + '/' + this.data.score+'/'+this.data.userInfo.id,
				method: 'GET',
			}).then(res => {
				if (res.statusCode == 200) {
					this.setData({
						mine: res.data.data.list == null ? this.data.mine : this.data.mine.concat(res.data.data.list),
						offset: res.data.data.offset,
            score: res.data.data.minTime,
            loadModal:false
					})
					console.log('score为' + this.data.score)
				} else {
          this.setData({
            loadModal:false
          })
					Notify('服务错误，稍后重试');
				}
			})
		}
	},
	onChange(event) {
		var name = event.detail.name
		console.log(name)
		if (name == 0) {
			console.log('进入条件')
			//切换到朋友圈做的逻辑
			this.setData({
				dynamics: [],
				offset: 0,
				score: Date.parse(new Date()),
				index: 0
			})
			this.getAllDynamicsByOffsetAndScore()
		} else {
			//切换到我的做的逻辑
			this.setData({
				mine: [],
				offset: 0,
				score: Date.parse(new Date()),
				index: 1
			})
			this.getMyDynamicsByOffsetAndScore()
		}
	},
	//跳转到新增界面
	gotoadd() {
		wx.navigateTo({
			url: '/pages/life/add/add?index=' + this.data.index,
		})
	},
	//点赞
	giveALike(item) {
		var dynamic = item.target.dataset.item
		var index = item.target.dataset.index
		app.request({
			url: app.globalData.apiUrl + '/dynamic/dianzan/' + dynamic.id,
			method: 'POST',
		}).then(res => {
			if (res.statusCode == 200) {
				dynamic.liked = 1;
				dynamic.likes = dynamic.likes + 1;
				this.setData({
					['dynamics[' + index + ']']: dynamic
				})
			} else {
				Notify('服务错误，稍后重试');
			}
		})
	},
	//取消赞
	cancelLike(item) {
		var dynamic = item.target.dataset.item
		var index = item.target.dataset.index
		app.request({
			url: app.globalData.apiUrl + '/dynamic/cancel/' + dynamic.id,
			method: 'POST',
		}).then(res => {
			if (res.statusCode == 200) {
				dynamic.liked = 0;
				dynamic.likes = dynamic.likes - 1
				this.setData({
					['dynamics[' + index + ']']: dynamic
				})
			} else {
				Notify('服务错误，稍后重试');
			}
		})
	},
	//点赞（我的）
	giveALikeMine(item) {
		var dynamic = item.target.dataset.item
		var index = item.target.dataset.index
		app.request({
			url: app.globalData.apiUrl + '/dynamic/dianzan/' + dynamic.id,
			method: 'POST',
		}).then(res => {
			if (res.statusCode == 200) {
				dynamic.liked = 1;
				dynamic.likes = dynamic.likes + 1;
				this.setData({
					['mine[' + index + ']']: dynamic
				})
			} else {
				Notify('服务错误，稍后重试');
			}
		})
	},
	//取消赞(我的)
	cancelLikeMine(item) {
		var dynamic = item.target.dataset.item
		var index = item.target.dataset.index
		app.request({
			url: app.globalData.apiUrl + '/dynamic/cancel/' + dynamic.id,
			method: 'POST',
		}).then(res => {
			if (res.statusCode == 200) {
				dynamic.liked = 0;
				dynamic.likes = dynamic.likes - 1
				this.setData({
					['mine[' + index + ']']: dynamic
				})
			} else {
				Notify('服务错误，稍后重试');
			}
		})
	},
	getLikes(id) {
		app.request({
			url: app.globalData.apiUrl + '/dynamic/likes/' + id,
			method: 'GET',
		}).then(res => {
			if (res.statusCode == 200) {
				return res.data.data;
			} else {}
		})
	},
	updateDynamic(item) {
		//携带参数页面跳转
		var dynamic = JSON.stringify(item.target.dataset.item)
		wx.navigateTo({
			url: '/pages/life/update/update?dynamic=' + dynamic,
		})
	},
	deleteDynamic() {
		//弹出模态框,携带删除文章的id,可以把这个id存入页面data中，点击模态框的确认键后直接从data取这个id去进行删除。
		app.request({
			url: app.globalData.apiUrl + '/dynamic/' + this.data.temp,
			method: 'DELETE',
		}).then(res => {
			if (res.statusCode == 200) {
				Notify('删除动态成功');
				this.onShow()
			} else {
				Notify('服务错误，稍后重试');
			}
		})
		this.hideModal()
	},
	showModal(e) {
    this.setData({
			modalName: e.currentTarget.dataset.target,
			temp:e.currentTarget.dataset.id
		})
		console.log(this.data.temp)
  },
  hideModal(e) {
    this.setData({
      modalName: null
    })
	},
	gotoCommit(item){
		var dynamic = JSON.stringify(item.target.dataset.item)
		wx.navigateTo({
			url: '/pages/life/comment/comment?dynamic='+dynamic,
		})
	}
})